package model.gallery;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;

import model.member.MemberVO;
import model.util.BestPagingBean;
import model.util.CommonConstants;
import model.util.ListVO;
import model.util.MakeThumbnail;
import model.util.PagingBean;
import model.util.ReplyVO;

import org.springframework.web.multipart.MultipartFile;

public class GalleryService {
	private GalleryDao dao;
	private String thumb_path;
	private String orgImg_path;
	public GalleryService() {
		super();
		// TODO Auto-generated constructor stub
	}

	public GalleryService(GalleryDao dao, String thumb_path, String orgImg_path) {
		super();
		this.dao = dao;
		this.thumb_path = thumb_path;
		this.orgImg_path = orgImg_path;
	}
	public void makeThumbnail(MultipartFile mf, int size, String path){
		BufferedImage img = null; //업로드한 파일을 이미지로 변환하기 위해 BufferedImage 변수 선언
		try {
			//업로드한 파일의 InputStream을 이용해 BufferedImage로 받아 이미지로 만듬
			img = ImageIO.read(mf.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// static으로 선언한 makeThumbnail 메서드를 사용해 업로드한 프로필 이미지의 사이즈를 조절해 저장
		MakeThumbnail.makeThumbnail((BufferedImage)img, size, path);	
	}
	public void write(GalleryVO vo) throws SQLException{
		MultipartFile mfile = vo.getUploadImg();
		if(mfile.isEmpty()==false){
			long now = System.currentTimeMillis();
			vo.setOrgImgName(now+"_"+mfile.getOriginalFilename());
			String thumbName = "thumb_"+vo.getOrgImgName().substring(0, vo.getOrgImgName().indexOf("."))+".png";
			vo.setThumbImgName(thumbName);
			makeThumbnail(mfile, 200, thumb_path+thumbName);
			File orgFile = new File(orgImg_path+vo.getOrgImgName());
			try {
				mfile.transferTo(orgFile);
			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				orgFile.delete();
				File thumb = new File(thumb_path+thumbName);
				thumb.delete();
			}
		}
		vo.setW_date(dao.getW_date());
		dao.write(vo);	
		vo.setNo(dao.getSeq());
		dao.wow_update(vo);
	}
	public HashMap content(int no, int uid) throws SQLException{
		HashMap map = new HashMap();
		dao.updateCount(no);
		GalleryVO gvo=dao.content(no);
		
		//--------------		추천관련 시작.1		-------------->				
		map.put("gvo", gvo); // 3. 셋팅된 추천수와함께 나머지 게시물정보를 map 투척	
		GalleryVO vo = new GalleryVO();
		vo.setNo(no); 
		vo.setMemberVO(new MemberVO(uid, null, null, null, null, null, null, null));
		if(vo.getMemberVO().getuId()!=0){ // 비로그인 사용자는 uid가 0으로 온다 0이 아니면 로그인사용자
		 String wow_check = dao.wow_check(vo); // 0이 아닌 로그인 사용자가 추천을 했는지 확인
		 map.put("wow_check", wow_check);
		}
		//--------------		추천관련 끝.1		-------------->
		
		return map;
	}
	//--------------		추천관련 시작.2		-------------->
	public void wow_update(GalleryVO vo) throws SQLException {		
		 dao.wow_update(vo);
		 dao.updateWow(vo.getNo());
	}

	public int wow_count(int no) throws SQLException {
		// TODO Auto-generated method stub
		return dao.wow_count(no);
	}
	//--------------		추천관련 끝.2		-------------->
	
	public ArrayList<Object> listByUser(int uId, int page) throws SQLException{
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("uId",uId);
		map.put("page",page);
		map.put("number", CommonConstants.USER_CONTENT_NUMBER_PER_PAGE);
		return dao.listByUser(map);
		
	}

	public void delete(int no, String orgImg, String thumbImg) throws SQLException {
		File orgFile = new File(orgImg_path+orgImg);
		File thumbFile = new File(thumb_path+thumbImg);
		orgFile.delete();
		thumbFile.delete();
		dao.delete(no);
	}
	
	public void update(GalleryVO vo) throws SQLException{
		MultipartFile mfile = vo.getUploadImg();
		if(mfile!=null){
			File orgFile = new File(orgImg_path+vo.getOrgImgName());
			File thumbFile = new File(thumb_path+vo.getThumbImgName());
			orgFile.delete();
			thumbFile.delete();
			
			long now = System.currentTimeMillis();
			vo.setOrgImgName(now+"_"+mfile.getOriginalFilename());
			String thumbName = "thumb_"+vo.getOrgImgName().substring(0, vo.getOrgImgName().indexOf("."))+".png";
			vo.setThumbImgName(thumbName);
			makeThumbnail(mfile, 200, thumb_path+thumbName);
			try {
				mfile.transferTo(orgFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				orgFile.delete();
				File thumb = new File(thumb_path+thumbName);
				thumb.delete();
			}
		}
		vo.setW_date(dao.getW_date());
		dao.update(vo);
	}
	public ListVO list(String category, String page) throws SQLException {
		// TODO Auto-generated method stub
		if(page==null||page==""){
			page="1";
		}
		HashMap map = new HashMap();
		map.put("category", category);
		map.put("page", page);
		map.put("number", CommonConstants.GALLERY_CONTENT_PER_PAGE);
		
		ArrayList<Object> list = (ArrayList<Object>) dao.list(map);
		int total = dao.totalContentByCategory(category);
		PagingBean paging=new PagingBean(total,Integer.parseInt(page),CommonConstants.GALLERY_CONTENT_PER_PAGE);
		
		ListVO lvo=new ListVO(list,paging);
		//System.out.println("service"+lvo);
		return lvo;
	}
		
	public ListVO getBest_weekly(String page) throws NumberFormatException, SQLException {
			
		if(page==null||page==""){
			page="1";
		}
		
		ArrayList<Object> list = (ArrayList<Object>) dao.getBest_Weekly(Integer.parseInt(page));
		int total = dao.getTotalBest();
		//System.out.println(total + "_________" + page);
		PagingBean paging=new BestPagingBean(total,Integer.parseInt(page), 8);
		paging.setNumberOfPageGroup(8);
		ListVO lvo = new ListVO(list,paging);
			return lvo;
	}
		
	
	
	
	
	/**
	 * gallery 쓰기 영역 
	 * @param gallery_no
	 * @param m_uid
	 * @param content
	 * @param restep
	 * @throws SQLException
	 */
	
	public void reply_write(int gallery_no, String m_uid,
			String content, int restep) throws SQLException {
		HashMap map = new HashMap();
		map.put("gallery_no", gallery_no);
		map.put("m_uid", m_uid);
		map.put("content", content);
		map.put("restep", restep);
		dao.reply_write(map);
		
	}

	public ArrayList<ReplyVO> reply_view(int gallery_no) throws SQLException {
		// TODO Auto-generated method stub
		return (ArrayList<ReplyVO>) dao.reply_view(gallery_no);
	}

	public void reply_delte(ReplyVO vo) throws SQLException {
		dao.reply_delete(vo);
		dao.updateRestep(vo);
	}

	public int getRestep(int gallery_no) throws SQLException {
		// TODO Auto-generated method stub
		return dao.getRestep(gallery_no);
	}
	
	public HashMap list_best() throws SQLException{	
		List<GalleryVO> pList=dao.list_best("practice");
		List<GalleryVO> sList=dao.list_best("series");
		List<GalleryVO> aList=dao.list_best("art");
		HashMap<String,List<GalleryVO>> map=new HashMap();
		map.put("pList", pList);
		map.put("sList", sList);
		map.put("aList", aList);
		//System.out.println(map);
		return  map;	
	}

	public HashMap weekly(int bestPrimary) throws SQLException {
		List<GalleryVO> pList=dao.weekly("practice",bestPrimary);
		List<GalleryVO> sList=dao.weekly("series",bestPrimary);
		List<GalleryVO> aList=dao.weekly("art",bestPrimary);
		HashMap<String,List<GalleryVO>> map=new HashMap();

		map.put("pList", pList);
		map.put("sList", sList);
		map.put("aList", aList);
		return map;
		
	}

	
}
